/*
 * Orange navigation v1.0.0
 * Copyright 2016 XiaoXiong
 */
(function() {
	'use strict';
	
	//	定义导航组件，依赖juqery
	define('navigation', ['jquery'], function($) {
		if (typeof jQuery === 'undefined') {
		    throw new Error('组件[navigation]加载失败，缺少依赖[jquery]');
		}
		//	导航组件
		var navigation = {};
		
		//	默认设置
		var _Defaults = {
			
			// [{title: '标题', icon: '图标', url: '请求路径'}]
			data: [],
			
			// [{title: 'name'}, {}, {}]
			field: {},
			
			//	图标默认颜色
			dColor: '#313233',
			
			//	图标颜色组
			colors: ['#0000ff', '#62ca41', '#bfbc1d', '#de6637', '#be37de'],
				
			// 设置选中页签，index/title
			selected: undefined,
			
			//	TITLE、ICON
			type: 'TITLE',
			
			//	LEFT、TOP、RIGTH、BOTTOM、SUBTOP
			position: 'TOP',
			
			//	选择事件，当导航页签被选中时触发
			onSelect: function(item, index) {},
			
			//	加载完成事件，当导航加载完成时触发
			onLoaded: function(element) {}
		};
		
		//	组件方法
		var Methods = {
			create: create,
			selectItem: selectItem,
			getItemData: getItemData
		};
		
		//	创建组件，参数：目标元素、组件参数
		function create(element, options) {
			var element = $(element), opts = $.extend({}, this, options), navigation = $.extend({element:element}, opts), 
				data = opts['data'], position = typeof opts['position'] === 'string'?opts['position'].toUpperCase() : opts['position'], 
				selected = opts['selected'], type = typeof opts['type'] === 'string'?opts['type'].toUpperCase() : opts['type'],
				field = options.field;
			
			if(!data || !data instanceof Array) {
				throw new Error('组件[navigation]创建失败，参数[data]非法');
			}
				
			//	创建左部导航
			if(position === 'LEFT') {
				element.attr('class', 'nav-collapse navigation navigation-left navigation-icon');
				element = $('<ul/>').appendTo(element);
				_createItem(type, element, data, field);
			}
			
			//	创建顶部导航
			if(position === 'TOP') {
				element.attr('class','row clearfix navigation navigation-maintop navigation-top');
				element = $('<ul class="col-md-12 column"/>').appendTo(element);
				_createItem(type, element, data, field);
				
			}
			
			//	创建顶部导航的下级导航
			if(position === 'SUBTOP') {
				element.attr('class',' row clearfix navigation navigation-subtop navigation-top');
				element = $('<ul class="col-md-12 column"/>').appendTo(element);
				_createItem(type, element, data, field);
			}
			
			//	创建顶部下级导航的另外一种形式
			if(position === 'SUBTOPLARGE') {
				element.attr('class',' row clearfix navigation navigation-subtop navigation-top large');
				element = $('<ul class="col-md-12 column"/>').appendTo(element);
				_createItem(type, element, data, field);
			}
			
			//	创建右部导航
			
			
			//	创建底部导航
			
			if(selected) {
				navigation.selectItem(selected);
			}
			_bindEvents(navigation);
			_triggerEvent('Loaded', [element], navigation);
			return navigation;
		}
		
		//	设置页签为选中状态, item已经是jquery对象，所以
		function _setSelected(item, navigation) {
			var index = item.attr('index');
			if(!item.attr('disabled') && true) {
				if(navigation.position == 'TOP' || navigation.position == 'SUBTOP' || navigation.position =='SUBTOPLARGE') {
					//找到被选中的li
					if(!item.hasClass('selected')) {
						item.parent().find('li').each(function(){
							$(this).removeClass('selected');
		                });
						if(item instanceof jQuery) {
							item.addClass('selected');
						} else {
							$(item).addClass('selected');
						}
					}
				} else if(navigation.position == 'LEFT'){
					$('.navigation .icon').css('color', navigation.dColor);
					$($(item)[0]).addClass('selected').siblings().removeClass("selected");
				}
				_triggerEvent('Select', [navigation.getItemData(index), {'index': index}], navigation);
			}
		}
		
		
		//	选中页签
		//	param: index/title
		//	index: 页签顺序, title: 页签标题
		function selectItem(param) {
			var item = undefined, self = this, element = self.element;
			if(!isNaN(param)) {
				item = element.find('li')[param];
			} else {
				var data = self.data, length = data.length;
				for(var i=0; i<length; i++) {
					if(data[i]['title'] == param) {
						item = element.find('li')[i];
						break;
					}
				}
			}
			if(!item) {
				throw new Error('导航页签选中失败，不存在此页签');
			}
			_setSelected($(item), self);
			return self;
		}
		
		//	获取页签数据
		function getItemData(index) {
			return this.data[index];
		}
		
		/*function _createItem(type, element, data) {
			if(type === 'TITLE') {
				for(var i=0; i<data.length; i++) {
					element.append('<li index='+ i +'><a href="#">' + data[i]['title'] + '</a></li>');
				}
			} else if(type === 'ICON') {
				for(var i=0; i<data.length; i++) {
					element.append('<li index='+ i +'><a><i class="icon iconfont" title="'+ 
							data[i]['title'] +'">'+ data[i]['icon'] +'</i></a></li>');
				}
			} else {
				return;
			}
		}*/
		//创建导航页签(添加了有field的情况)
		function _createItem(type, element, data, field) {
			if(type === 'TITLE') {
				if(field != null && field instanceof Object) {
					for(var i=0; i<data.length; i++) {
						element.append('<li index='+ i +'><a href="#" title="' + data[i][field['title']] + '">'
								+ data[i][field['title']] + '</a></li>');
					}
				} else {
					for(var i=0; i<data.length; i++) {
						element.append('<li index='+ i +'><a href="#">' + data[i]['title'] + '</a></li>');
					}
				}
			} else if(type === 'ICON') {
				for(var i=0; i<data.length; i++) {
					element.append('<li index="' + i + '"><a><img title="' + data[i][field['title']] 
					+ '" src="' + data[i][field['icon']] + '"/></a></li>');
				} 
				//备份，字体图标
				/*for(var i=0; i<data.length; i++) {
					element.append('<li index='+ i +'><a><i class="icon iconfont" title="'+ 
							data[i][field['title']] +'">'+ data[i][field['icon']] +'</i></a></li>');
				}*/
				
			} else {
				return;
			}
		}
		
		//	绑定事件
		function _bindEvents(navigation) {
			_bindSelect(navigation);
		}
		
		//	触发事件
		function _triggerEvent(event, params, nav) {
			var callback = 'on' + event;
			if(!nav[callback]) {
				return;
			}
			nav[callback].apply(nav[callback], params);
		}
		
		//	绑定导航页签选中事件
		function _bindSelect(navigation) {
			
			navigation.element.find('li').bind('click', function(e) {
				var item = $(this);
				_setSelected(item, navigation);
			});
			
		}
		
		//	初始化组件
		function _init() {
			for(var i in _Defaults) {
				navigation[i] = _Defaults[i];
			}
			
			for(var i in Methods) {
				navigation[i] = Methods[i];
			}
			return navigation;
		}
		
		return _init();
	});
})();
